<template>
  <el-dialog
    v-model="dialogVisible"
    title="文章审核"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <div v-loading="loading" class="audit-dialog">
      <!-- 文章信息 -->
      <el-card class="article-info" shadow="never">
        <template #header>
          <span class="card-title">文章信息</span>
        </template>

        <div v-if="props.article" class="article-summary">
          <div class="info-row">
            <span class="label">标题：</span>
            <span class="value">{{ props.article.title }}</span>
          </div>
          <div class="info-row">
            <span class="label">作者：</span>
            <span class="value">{{ props.article.authorNickName }}</span>
          </div>
          <div class="info-row">
            <span class="label">分类：</span>
            <el-tag type="primary" size="small">{{
              props.article.categoryName
            }}</el-tag>
          </div>
          <div class="info-row">
            <span class="label">状态：</span>
            <el-tag
              :type="
                ArticleManagementUtils.getStatusTagType(props.article.status)
              "
              size="small"
            >
              {{ ArticleManagementUtils.getStatusText(props.article.status) }}
            </el-tag>
          </div>
          <div class="info-row">
            <span class="label">字数：</span>
            <span class="value">{{
              ArticleManagementUtils.formatNumber(props.article.wordCount)
            }}</span>
          </div>
          <div class="info-row">
            <span class="label">创建时间：</span>
            <span class="value">{{ props.article.createTime }}</span>
          </div>
        </div>
      </el-card>

      <!-- 审核表单 -->
      <el-card class="audit-form" shadow="never">
        <template #header>
          <span class="card-title">审核信息</span>
        </template>

        <el-form
          ref="auditFormRef"
          :model="auditForm"
          :rules="auditRules"
          label-width="100px"
        >
          <el-form-item label="审核结果" prop="auditResult" required>
            <el-radio-group v-model="auditForm.auditResult">
              <el-radio
                v-for="option in AUDIT_RESULT_OPTIONS"
                :key="option.value"
                :value="option.value"
                :class="option.type"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="审核备注" prop="auditRemark">
            <el-input
              v-model="auditForm.auditRemark"
              type="textarea"
              :rows="3"
              placeholder="请输入审核备注（必填）"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="审核原因" prop="auditReason">
            <el-input
              v-model="auditForm.auditReason"
              type="textarea"
              :rows="2"
              placeholder="请输入审核原因（可选）"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="改进建议" prop="suggestions">
            <el-input
              v-model="auditForm.suggestions"
              type="textarea"
              :rows="2"
              placeholder="请输入改进建议（可选）"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="通知设置">
            <el-checkbox v-model="auditForm.sendNotification">
              发送审核结果通知给作者
            </el-checkbox>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 快速审核模板 -->
      <el-card class="quick-templates" shadow="never">
        <template #header>
          <span class="card-title">快速审核模板</span>
        </template>

        <div class="template-buttons">
          <el-button
            v-for="template in auditTemplates"
            :key="template.id"
            :type="template.type"
            size="small"
            @click="applyTemplate(template)"
          >
            {{ template.name }}
          </el-button>
        </div>
      </el-card>

      <!-- 文章预览 -->
      <el-card class="article-preview" shadow="never">
        <template #header>
          <div class="preview-header">
            <span class="card-title">文章预览</span>
            <el-button-group size="small">
              <el-button
                :type="previewMode === 'summary' ? 'primary' : 'default'"
                @click="previewMode = 'summary'"
              >
                摘要
              </el-button>
              <el-button
                :type="previewMode === 'content' ? 'primary' : 'default'"
                @click="previewMode = 'content'"
              >
                内容
              </el-button>
            </el-button-group>
          </div>
        </template>

        <div class="preview-content">
          <!-- 摘要预览 -->
          <div v-if="previewMode === 'summary'" class="summary-preview">
            <p>{{ props.article?.summary || "暂无摘要" }}</p>
          </div>

          <!-- 内容预览 -->
          <div v-else-if="previewMode === 'content'" class="content-preview">
            <div v-if="loading" class="loading-content">
              <el-skeleton :rows="5" animated />
            </div>
            <div v-else-if="!articleDetail" class="no-article">
              <el-empty description="暂无文章数据" />
            </div>
            <div
              v-else-if="!articleDetail.content && !articleDetail.htmlContent"
              class="no-content"
            >
              <el-empty description="文章内容为空">
                <template #description>
                  <p>该文章暂无内容数据</p>
                  <p>文章ID: {{ articleDetail.id }}</p>
                  <p>请检查后端数据或联系管理员</p>
                </template>
              </el-empty>
            </div>
            <MarkdownPreview
              v-else
              :content="articleDetail.content || ''"
              :html-content="articleDetail.htmlContent || ''"
              :enable-refresh="false"
            />
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          提交审核
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  auditArticleApi,
  getArticleDetailApi,
  type ArticleInfo,
  type ArticleDetail,
  type ArticleAuditParams,
  ArticleManagementUtils
} from "@/api/article-management";
import { AUDIT_RESULT_OPTIONS, MESSAGES } from "@/constants/article";
import MarkdownPreview from "./MarkdownPreview.vue";

defineOptions({
  name: "ArticleAuditDialog"
});

// Props
interface Props {
  visible: boolean;
  article: ArticleInfo | null;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  refresh: [];
}>();

// 响应式数据
const loading = ref(false);
const previewMode = ref<"summary" | "content">("summary");
const auditFormRef = ref<FormInstance>();
const articleDetail = ref<ArticleDetail | null>(null);

// 审核表单
const auditForm = reactive<ArticleAuditParams>({
  articleId: 0,
  auditResult: 1,
  auditRemark: "",
  auditReason: "",
  suggestions: "",
  sendNotification: true
});

// 表单验证规则
const auditRules: FormRules = {
  auditResult: [
    { required: true, message: "请选择审核结果", trigger: "change" }
  ],
  auditRemark: [
    { required: true, message: "请输入审核备注", trigger: "blur" },
    {
      min: 5,
      max: 500,
      message: "审核备注长度在 5 到 500 个字符",
      trigger: "blur"
    }
  ]
};

// 审核模板
const auditTemplates = [
  {
    id: 1,
    name: "内容优质，通过",
    type: "success",
    result: 1,
    remark: "文章内容质量良好，符合发布标准，审核通过。",
    reason: "内容原创且有价值",
    suggestions: ""
  },
  {
    id: 2,
    name: "格式规范，通过",
    type: "success",
    result: 1,
    remark: "文章格式规范，内容完整，审核通过。",
    reason: "格式符合要求",
    suggestions: ""
  },
  {
    id: 3,
    name: "内容违规，拒绝",
    type: "danger",
    result: 4,
    remark: "文章内容存在违规问题，不符合发布标准。",
    reason: "内容违反社区规范",
    suggestions: "请修改违规内容后重新提交"
  },
  {
    id: 4,
    name: "质量不佳，拒绝",
    type: "danger",
    result: 4,
    remark: "文章质量不符合发布标准，建议完善后重新提交。",
    reason: "内容质量有待提升",
    suggestions: "建议增加更多有价值的内容，完善文章结构"
  },
  {
    id: 5,
    name: "格式问题，拒绝",
    type: "warning",
    result: 4,
    remark: "文章格式存在问题，影响阅读体验。",
    reason: "格式不规范",
    suggestions: "请调整文章格式，确保排版整齐"
  }
];

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

// 获取文章详情
const loadArticleDetail = async (articleId: number) => {
  try {
    loading.value = true;
    console.log("ArticleAuditDialog - 开始获取文章详情:", articleId);

    const response = await getArticleDetailApi(articleId);
    const { data } = response;

    if (data?.code === 200 && data.data) {
      articleDetail.value = data.data;
      console.log("ArticleAuditDialog - 文章详情获取成功:", {
        id: articleDetail.value.id,
        title: articleDetail.value.title,
        hasContent: !!articleDetail.value.content,
        contentLength: articleDetail.value.content?.length || 0,
        hasHtmlContent: !!articleDetail.value.htmlContent,
        htmlContentLength: articleDetail.value.htmlContent?.length || 0
      });
    } else if (data?.id && data?.title) {
      // 兼容直接返回详情的格式
      articleDetail.value = data;
      console.log("ArticleAuditDialog - 使用直接格式，文章详情:", {
        id: articleDetail.value.id,
        title: articleDetail.value.title,
        hasContent: !!articleDetail.value.content,
        contentLength: articleDetail.value.content?.length || 0,
        hasHtmlContent: !!articleDetail.value.htmlContent,
        htmlContentLength: articleDetail.value.htmlContent?.length || 0
      });
    } else {
      console.warn("ArticleAuditDialog - 响应数据格式异常:", data);
      ElMessage.error("文章详情数据格式异常");
    }
  } catch (error) {
    console.error("ArticleAuditDialog - 获取文章详情失败:", error);
    ElMessage.error("获取文章详情失败");
  } finally {
    loading.value = false;
  }
};

// 监听文章变化
watch(
  () => props.article,
  newArticle => {
    console.log("ArticleAuditDialog - 文章数据变化:", {
      hasArticle: !!newArticle,
      articleId: newArticle?.id,
      title: newArticle?.title,
      status: newArticle?.status
    });

    if (newArticle) {
      auditForm.articleId = newArticle.id;
      // 重置表单
      auditForm.auditResult = 1;
      auditForm.auditRemark = "";
      auditForm.auditReason = "";
      auditForm.suggestions = "";
      auditForm.sendNotification = true;

      // 获取完整的文章详情
      loadArticleDetail(newArticle.id);
    } else {
      // 清空文章详情
      articleDetail.value = null;
    }
  },
  { immediate: true }
);

// 应用审核模板
const applyTemplate = (template: any) => {
  auditForm.auditResult = template.result;
  auditForm.auditRemark = template.remark;
  auditForm.auditReason = template.reason;
  auditForm.suggestions = template.suggestions;
};

// 提交审核
const handleSubmit = async () => {
  if (!auditFormRef.value) return;

  try {
    await auditFormRef.value.validate();

    const confirmMessage =
      auditForm.auditResult === 1
        ? MESSAGES.CONFIRM.AUDIT_APPROVE
        : MESSAGES.CONFIRM.AUDIT_REJECT;

    await ElMessageBox.confirm(confirmMessage, "确认审核", {
      type: "warning"
    });

    loading.value = true;
    await auditArticleApi(auditForm);

    const successMessage =
      auditForm.auditResult === 1
        ? MESSAGES.SUCCESS.AUDIT_APPROVE
        : MESSAGES.SUCCESS.AUDIT_REJECT;

    ElMessage.success(successMessage);
    emit("refresh");
    handleCancel();
  } catch (error) {
    if (error !== "cancel") {
      console.error("审核失败:", error);
      ElMessage.error(MESSAGES.ERROR.OPERATION_FAILED);
    }
  } finally {
    loading.value = false;
  }
};

// 取消审核
const handleCancel = () => {
  auditFormRef.value?.resetFields();
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 768px) {
  .audit-dialog {
    .preview-header {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
    }

    .template-buttons {
      justify-content: center;
    }

    .article-summary {
      .info-row {
        flex-direction: column;
        gap: 4px;
        align-items: flex-start;

        .label {
          width: auto;
        }
      }
    }
  }
}

.audit-dialog {
  .article-info,
  .audit-form,
  .quick-templates,
  .article-preview {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .article-summary {
    .info-row {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 80px;
        font-weight: 500;
        color: #606266;
      }

      .value {
        flex: 1;
        color: #303133;
      }
    }
  }

  .audit-form {
    :deep(.el-form-item__label) {
      font-weight: 500;
    }

    :deep(.el-radio.success) {
      .el-radio__label {
        color: #67c23a;
      }
    }

    :deep(.el-radio.danger) {
      .el-radio__label {
        color: #f56c6c;
      }
    }
  }

  .template-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .preview-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .preview-content {
    min-height: 200px;

    .summary-preview {
      padding: 16px;
      line-height: 1.6;
      color: #606266;
      background-color: #f5f7fa;
      border-radius: 4px;
    }

    .content-preview {
      max-height: 400px;
      overflow-y: auto;

      .loading-content,
      .no-article,
      .no-content {
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 200px;
        background-color: #fafafa;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
      }

      .loading-content {
        padding: 20px;

        :deep(.el-skeleton) {
          width: 100%;
        }
      }

      .no-article,
      .no-content {
        :deep(.el-empty__description) {
          p {
            margin: 4px 0;
            font-size: 14px;
            color: #909399;

            &:first-child {
              font-weight: 500;
              color: #606266;
            }
          }
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
